package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class TcpEchoServer3 {
    ServerSocket serverSocket = null;
    TcpEchoServer3(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        System.out.printf("[%s:%d] 服务器启动\n", serverSocket.getInetAddress(), serverSocket.getLocalPort());

    }
    public void start() throws IOException {
        ExecutorService service = Executors.newCachedThreadPool();
        while(true) {
            Socket socket = serverSocket.accept();
            service.submit(new Runnable(){
                @Override
                public void run() {
                    try {
                        solve(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    private void solve(Socket socket) throws IOException {
        System.out.printf("[%s:%d 服务器上线]", socket.getInetAddress(), socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                if(!scanner.hasNext()) {
                    System.out.printf("[%s:%d 服务器下线]", socket.getInetAddress(), socket.getPort());
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d req:%s rep:%s]\n",
                        socket.getInetAddress(),
                        socket.getPort(),
                        request,
                        response);
            }
        }finally {
            socket.close();
        }
    }
    private String process(String s) {
        return s;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer3 server3 = new TcpEchoServer3(1314);
        server3.start();
    }
}
